import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_bloc_demo/main/main_page_bloc.dart';

/// main page 主要演示利用bloc框架 获取点赞列表并进行点赞操作
class MainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MainPageState();
  }
}

class _MainPageState<MainPage> extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("mainPage"),
      ),
      body: Container(
        child: BlocProvider<MainPageBloc>(
          create: (BuildContext context) => MainPageBloc(),
          child: BlocBuilder<MainPageBloc, MainPageState>(
              builder: (BuildContext context, MainPageState state) {
                return ListView(
                  children: _buildList(context,state.list),
                );
              },),
        ),
      ),
    );
  }

  List<Widget> _buildList(BuildContext contextX, List<bool> likeList) {
    var list = likeList
        .asMap()
        .keys
        .map(
          (e) => Container(
            color: Colors.greenAccent,
            margin: EdgeInsets.all(20),
            padding: EdgeInsets.all(10),
            child: Row(
              children: [
                Text("第$e条新闻"),
                Container(
                    margin: EdgeInsets.only(left: 20),
                    child: GestureDetector(
                      onTap: () {
                        BlocProvider.of<MainPageBloc>(contextX).add(MainPageLikeEvent(e, !likeList[e]),);
                        // setState(() {
                        //   likeList[e] = !likeList[e];
                        //   print(likeList);
                        // });
                      },
                      child: Icon(
                        likeList[e] ? Icons.favorite : Icons.favorite_border,
                        color: Colors.blueAccent,
                      ),
                    )),
              ],
            ),
          ),
        )
        .toList();
    list.add(
      Container(
        child: ElevatedButton(
          onPressed: (){
            BlocProvider.of<MainPageBloc>(contextX).add(MainPageListEvent());
          },
          child: Text(
            "请求数据啊！",
          ),
        ),
      ),
    );
    return list;
  }
}
